<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Go并发编程学习的简单代码示例：生产者消费者模型 | 夜悊的技术小宅</title><meta name="author" content="夜悊"><meta name="copyright" content="夜悊"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="前言Go并发编程学习的简单代码示例：生产者消费者模型。  代码仓库 yezhening&#x2F;Programming-examples: 编程实例 (github.com) Programming-examples: 编程实例 (gitee.com)   核心概念并行和并发：  并行：同时运行多个任务。依赖硬件中央处理器（CPU）的数量或CPU的核心数量，CPU或CPU核心的数量越多，能够同时">
<meta property="og:type" content="article">
<meta property="og:title" content="Go并发编程学习的简单代码示例：生产者消费者模型">
<meta property="og:url" content="http://example.com/2023/04/16/Go%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E7%9A%84%E5%AD%A6%E4%B9%A0%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%EF%BC%9A%E7%94%9F%E4%BA%A7%E8%80%85%E6%B6%88%E8%B4%B9%E8%80%85%E6%A8%A1%E5%9E%8B/index.html">
<meta property="og:site_name" content="夜悊的技术小宅">
<meta property="og:description" content="前言Go并发编程学习的简单代码示例：生产者消费者模型。  代码仓库 yezhening&#x2F;Programming-examples: 编程实例 (github.com) Programming-examples: 编程实例 (gitee.com)   核心概念并行和并发：  并行：同时运行多个任务。依赖硬件中央处理器（CPU）的数量或CPU的核心数量，CPU或CPU核心的数量越多，能够同时">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/img/cover9.png">
<meta property="article:published_time" content="2023-04-16T05:06:47.000Z">
<meta property="article:modified_time" content="2023-04-26T07:52:13.332Z">
<meta property="article:author" content="夜悊">
<meta property="article:tag" content="Go">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/img/cover9.png"><link rel="shortcut icon" href="/img/favicon2.png"><link rel="canonical" href="http://example.com/2023/04/16/Go%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E7%9A%84%E5%AD%A6%E4%B9%A0%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%EF%BC%9A%E7%94%9F%E4%BA%A7%E8%80%85%E6%B6%88%E8%B4%B9%E8%80%85%E6%A8%A1%E5%9E%8B/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css?v=4.13.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0.33/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: 夜悊","link":"链接: ","source":"来源: 夜悊的技术小宅","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid@4.11.1/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Go并发编程学习的简单代码示例：生产者消费者模型',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-04-26 15:52:13'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><link rel="stylesheet" href="/css/my_css.css"><meta name="generator" content="Hexo 7.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/avatar.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">92</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">15</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-bookmark"></i><span> 笔记目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-blog"></i><span> 其他博客</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/m0_62083249"><i class="fa-fw fa fa-link"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/ye-zhe-ning"><i class="fa-fw fa fa-link"></i><span> 知乎</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-sitemap"></i><span> 代码仓库</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://gitee.com/yezhening"><i class="fa-fw fa fa-link"></i><span> Gitee</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://github.com/yezhening"><i class="fa-fw fa fa-link"></i><span> Github</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about_me/"><i class="fa-fw fas fa-user"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/cover9.png')"><nav id="nav"><span id="blog-info"><a href="/" title="夜悊的技术小宅"><span class="site-name">夜悊的技术小宅</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-bookmark"></i><span> 笔记目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-blog"></i><span> 其他博客</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/m0_62083249"><i class="fa-fw fa fa-link"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/ye-zhe-ning"><i class="fa-fw fa fa-link"></i><span> 知乎</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-sitemap"></i><span> 代码仓库</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://gitee.com/yezhening"><i class="fa-fw fa fa-link"></i><span> Gitee</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://github.com/yezhening"><i class="fa-fw fa fa-link"></i><span> Github</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about_me/"><i class="fa-fw fas fa-user"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Go并发编程学习的简单代码示例：生产者消费者模型</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-04-16T05:06:47.000Z" title="发表于 2023-04-16 13:06:47">2023-04-16</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-04-26T07:52:13.332Z" title="更新于 2023-04-26 15:52:13">2023-04-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Go/">Go</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Go并发编程学习的简单代码示例：生产者消费者模型"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>Go并发编程学习的简单代码示例：生产者消费者模型。</p>
<hr>
<h1 id="代码仓库"><a href="#代码仓库" class="headerlink" title="代码仓库"></a>代码仓库</h1><ul>
<li><a target="_blank" rel="noopener" href="https://github.com/yezhening/Programming-examples">yezhening&#x2F;Programming-examples: 编程实例 (github.com)</a></li>
<li><a target="_blank" rel="noopener" href="https://gitee.com/yezhening/Programming-examples">Programming-examples: 编程实例 (gitee.com)</a></li>
</ul>
<hr>
<h1 id="核心概念"><a href="#核心概念" class="headerlink" title="核心概念"></a>核心概念</h1><p>并行和并发：</p>
<ul>
<li>并行：同时运行多个任务。依赖硬件中央处理器（CPU）的数量或CPU的核心数量，CPU或CPU核心的数量越多，能够同时运行的程序&#x2F;进程越多</li>
<li>并发：宏观上是“同时运行”，微观&#x2F;实际上是在极短的时间内顺序运行多个程序&#x2F;进程</li>
</ul>
<p>进程、线程、协程和Go协程（goroutine）：</p>
<ul>
<li>进程：资源分配的基本单位</li>
<li>线程：<strong>内核态线程；</strong> CPU调度的基本单位</li>
<li>协程：<strong>用户态线程；轻量级线程</strong></li>
<li>一个进程可以有多个线程</li>
<li>线程和协程对应关系可以是一对一、一对多和多对多</li>
<li>goroutine：Go的协程概念，使用<strong>G（Goroutine）-P（Processor）-M（Machine）模型</strong></li>
</ul>
<p>Go的并发编程：</p>
<ul>
<li><p>使用go关键字开启多协程goroutine，而不是多进程和多线程，实现并发</p>
</li>
<li><p>使用管道channal，而不是锁，实现同步互斥和数据通信</p>
</li>
</ul>
<blockquote>
<p>可联想进程间通信（IPC）中的管道pipe()、共享内存等方式</p>
</blockquote>
<ul>
<li>使用select{}语句，实现监听输入&#x2F;输出（I&#x2F;O）操作</li>
</ul>
<blockquote>
<p>可联想网络编程中的监听文件描述符select()函数</p>
</blockquote>
<blockquote>
<p>相比于C、C++和其他语言，使用Go实现并发编程的逻辑很简单</p>
</blockquote>
<hr>
<h1 id="main-go（有详细注释）"><a href="#main-go（有详细注释）" class="headerlink" title="main.go（有详细注释）"></a>main.go（有详细注释）</h1><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main <span class="comment">// 一个工程只有一个main包</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 导入路径</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;fmt&quot;</span> <span class="comment">// 用于输出</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 生产者</span></span><br><span class="line"><span class="comment">// 参数：数据管道，单向只写；标志管道，单向只读</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">producer</span><span class="params">(data_channel <span class="keyword">chan</span>&lt;- <span class="type">int</span>, flag_channel &lt;-<span class="keyword">chan</span> <span class="type">bool</span>)</span></span> &#123;</span><br><span class="line">	<span class="comment">// 循环处理，接收到消费者标志后才退出循环和函数</span></span><br><span class="line">	data := <span class="number">0</span> <span class="comment">//生产者生产的数据</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span> &#123;</span><br><span class="line">		<span class="comment">// select&#123;&#125;语句监听输入/输出（I/O）操作</span></span><br><span class="line">		<span class="keyword">select</span> &#123;</span><br><span class="line">		<span class="keyword">case</span> data_channel &lt;- data: <span class="comment">//有数据写</span></span><br><span class="line">			data++</span><br><span class="line">		<span class="keyword">case</span> flag := &lt;-flag_channel: <span class="comment">//有标志读</span></span><br><span class="line">			fmt.Println(<span class="string">&quot;生产者读标志：&quot;</span>, flag, <span class="string">&quot;结束生产&quot;</span>)</span><br><span class="line">			<span class="keyword">return</span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 消费者</span></span><br><span class="line"><span class="comment">// 参数：数据管道，单向只读；标志管道，单向只写</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">consumer</span><span class="params">(data_channel &lt;-<span class="keyword">chan</span> <span class="type">int</span>, flag_channel <span class="keyword">chan</span>&lt;- <span class="type">bool</span>)</span></span> &#123;</span><br><span class="line">	<span class="comment">// 约定循环5次后，消费者停止消费，向生产者发送停止生产标志</span></span><br><span class="line">	<span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="number">5</span>; i++ &#123;</span><br><span class="line">		data := &lt;-data_channel <span class="comment">//读数据</span></span><br><span class="line">		fmt.Println(<span class="string">&quot;消费者读数据：&quot;</span>, data)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	flag_channel &lt;- <span class="literal">true</span> <span class="comment">//写标志</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 一个工程只有一个main()函数，是程序的唯一入口</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	data_channel := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="type">int</span>, <span class="number">0</span>)</span><br><span class="line">	<span class="comment">// 数据管道，生产者向消费者传输数据</span></span><br><span class="line">	<span class="comment">// 传输int类型数据，0：无缓冲，双向</span></span><br><span class="line">	flag_channel := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="type">bool</span>, <span class="number">0</span>)</span><br><span class="line">	<span class="comment">// 标志管道，消费者向生产者传输标志，消费者不再消费，让生产者停止生产</span></span><br><span class="line">	<span class="comment">// 传输bool类型数据，0：无缓冲，双向</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">go</span> consumer(data_channel, flag_channel) <span class="comment">//go关键字开启goroutine处理消费者任务</span></span><br><span class="line"></span><br><span class="line">	producer(data_channel, flag_channel) <span class="comment">// main()中是主goroutine，处理生产者任务</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<hr>
<h1 id="结果"><a href="#结果" class="headerlink" title="结果"></a>结果</h1><figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">PS</span> C:\Users\DSHH\Desktop\go_test&gt; go run main.go</span><br><span class="line">消费者读数据： <span class="number">0</span></span><br><span class="line">消费者读数据： <span class="number">1</span></span><br><span class="line">消费者读数据： <span class="number">2</span></span><br><span class="line">消费者读数据： <span class="number">3</span></span><br><span class="line">消费者读数据： <span class="number">4</span></span><br><span class="line">生产者读标志： true 结束生产</span><br><span class="line"><span class="built_in">PS</span> C:\Users\DSHH\Desktop\go_test&gt; </span><br></pre></td></tr></table></figure>
<hr>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>Go并发编程的学习代码示例：生产者消费者模型。</p>
<hr>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><ul>
<li><a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1UW411x7Ve/?spm_id_from=333.337.search-card.all.click">20个小时快速入门go语言（中）_哔哩哔哩_bilibili</a></li>
<li><a target="_blank" rel="noopener" href="https://juejin.cn/post/7044741465930465311">一文看懂Go语言协程的设计与原理 - 掘金 (juejin.cn)</a></li>
</ul>
<hr>
<h1 id="作者的话"><a href="#作者的话" class="headerlink" title="作者的话"></a>作者的话</h1><ul>
<li><strong>感谢参考资料的作者&#x2F;博主</strong></li>
<li>作者：夜悊</li>
<li>版权所有，转载请注明出处，谢谢~</li>
<li><strong>如果文章对你有帮助，请点个赞或加个粉丝吧，你的支持就是作者的动力~</strong></li>
<li>文章在描述时有疑惑的地方，请留言，定会一一耐心讨论、解答</li>
<li>文章在认识上有错误的地方, 敬请批评指正</li>
<li>望读者们都能有所收获</li>
</ul>
<hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://example.com">夜悊</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/04/16/Go%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E7%9A%84%E5%AD%A6%E4%B9%A0%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%EF%BC%9A%E7%94%9F%E4%BA%A7%E8%80%85%E6%B6%88%E8%B4%B9%E8%80%85%E6%A8%A1%E5%9E%8B/">http://example.com/2023/04/16/Go并发编程的学习代码示例：生产者消费者模型/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">夜悊的技术小宅</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Go/">Go</a></div><div class="post_share"><div class="social-share" data-image="/img/cover9.png" data-sites="qq,wechat,weibo"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1.1.3/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1.1.3/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/04/14/Go%E7%9A%84%E5%B7%A5%E7%A8%8B%E7%AE%A1%E7%90%86/" title="Go的工程管理"><img class="cover" src= "" data-lazy-src="/img/cover16.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Go的工程管理</div></div></a></div><div class="next-post pull-right"><a href="/2023/04/17/Go%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E7%9A%84%E5%AD%A6%E4%B9%A0%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%EF%BC%9A%E5%AE%A2%E6%88%B7%E7%AB%AF_%E6%9C%8D%E5%8A%A1%E7%AB%AF%EF%BC%88C_S%EF%BC%89%E6%A8%A1%E5%9E%8B/" title="Go网络编程的学习代码示例：客户端/服务端（C/S）模型"><img class="cover" src= "" data-lazy-src="/img/cover3.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Go网络编程的学习代码示例：客户端/服务端（C/S）模型</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/04/14/Go%E7%9A%84%E5%B7%A5%E7%A8%8B%E7%AE%A1%E7%90%86/" title="Go的工程管理"><img class="cover" src= "" data-lazy-src="/img/cover16.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-14</div><div class="title">Go的工程管理</div></div></a></div><div><a href="/2023/04/17/Go%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E7%9A%84%E5%AD%A6%E4%B9%A0%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%EF%BC%9A%E5%AE%A2%E6%88%B7%E7%AB%AF_%E6%9C%8D%E5%8A%A1%E7%AB%AF%EF%BC%88C_S%EF%BC%89%E6%A8%A1%E5%9E%8B/" title="Go网络编程的学习代码示例：客户端&#x2F;服务端（C&#x2F;S）模型"><img class="cover" src= "" data-lazy-src="/img/cover3.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-17</div><div class="title">Go网络编程的学习代码示例：客户端&#x2F;服务端（C&#x2F;S）模型</div></div></a></div><div><a href="/2023/04/18/Go%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E7%9A%84%E5%AD%A6%E4%B9%A0%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%EF%BC%9A%E7%BD%91%E7%BB%9C%E6%96%87%E4%BB%B6%E4%BC%A0%E8%BE%93/" title="Go网络编程的学习代码示例：网络文件传输"><img class="cover" src= "" data-lazy-src="/img/cover10.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-18</div><div class="title">Go网络编程的学习代码示例：网络文件传输</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E4%BB%93%E5%BA%93"><span class="toc-number">2.</span> <span class="toc-text">代码仓库</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5"><span class="toc-number">3.</span> <span class="toc-text">核心概念</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#main-go%EF%BC%88%E6%9C%89%E8%AF%A6%E7%BB%86%E6%B3%A8%E9%87%8A%EF%BC%89"><span class="toc-number">4.</span> <span class="toc-text">main.go（有详细注释）</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BB%93%E6%9E%9C"><span class="toc-number">5.</span> <span class="toc-text">结果</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">6.</span> <span class="toc-text">总结</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="toc-number">7.</span> <span class="toc-text">参考资料</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%9C%E8%80%85%E7%9A%84%E8%AF%9D"><span class="toc-number">8.</span> <span class="toc-text">作者的话</span></a></li></ol></div></div></div></div></main><footer id="footer" style="background-image: url('/img/cover9.png')"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2025 By 夜悊</div><div class="footer_custom_text"><a target="_blank" href="https://beian.miit.gov.cn/" >琼ICP备2023001225号-1</a><br><img src= "" data-lazy-src="/img/beian.png"/>&nbsp<a target="_blank" href="https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=46010802001221" >琼公网安备 46010802001221号</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="translateLink" type="button" title="简繁转换">繁</button><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js?v=4.13.0"></script><script src="/js/main.js?v=4.13.0"></script><script src="/js/tw_cn.js?v=4.13.0"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0.33/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.8.8/dist/lazyload.iife.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js?v=4.13.0"></script></div></div></body></html>